package com.topscore.uke.ui.fragments;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.topscore.uke.R;
import com.topscore.uke.entities.HomeBannerInfo;
import com.topscore.uke.entities.HomeMenuItem;
import com.topscore.uke.entities.UserInfo;
import com.topscore.uke.entities.UserSalesInfo;
import com.topscore.uke.main.Contracts;
import com.topscore.uke.mvp.contractors.GetHomePageBannerContractor;
import com.topscore.uke.mvp.contractors.GetUserSalesContractor;
import com.topscore.uke.mvp.presenters.GetHomeBannerPresenter;
import com.topscore.uke.mvp.presenters.GetUserSaleInfoPresenter;
import com.topscore.uke.ui.BaseSupportFragment;
import com.topscore.uke.ui.activities.MyCouponActivity;
import com.topscore.uke.ui.activities.MyGoldCoinsActivity;
import com.topscore.uke.ui.activities.MyIncomeActivity;
import com.topscore.uke.ui.activities.MyMembersActivity;
import com.topscore.uke.ui.activities.MyPerformanceActivity;
import com.topscore.uke.ui.activities.MySalePerformanceActivity;
import com.topscore.uke.ui.activities.MyTeamActivity;
import com.topscore.uke.ui.activities.UkePerformanceActivity;
import com.topscore.uke.ui.activities.VisitorsActivity;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.loadsir_callback.LoadingCallBack;
import com.topscore.uke.utils.DisplayImageOptionsManager;
import com.topscore.uke.utils.UserInfoManager;
import com.topscore.utillibrary.widget.cyclebannerview.BannerData;
import com.topscore.utillibrary.widget.cyclebannerview.CirculatingBannerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomePageFragment extends BaseSupportFragment {

    @Bind(R.id.tool_bar)
    Toolbar toolBar;
    @Bind(R.id.root_recycler)
    RecyclerView rootRecycler;

    private ImageView mAvatar_Distributor, mAvatar_normal;
    private CirculatingBannerView mBannerView;
    private RecyclerView mMenu_Recycler_Distributor, mMenu_Recycler_Normal;

    private List<HomeMenuItem> mMenuItemList_Distributor, mMenuItemList_Normal;

    private View rootView;

    private List<MultiItem> mViewItems_Distributor;

    private final int _Header_Distributor = 1001, _Header_Normal = 1004;
    private final int _Banner = 1002;
    private final int _Menu_Distributor = 1003, _Menu_Normal = 1005;

    private RootAdapter mAdapter;

    public HomePageFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_home_page, container, false);
        ButterKnife.bind(this, rootView);
        initViews();
        return rootView;
    }

    private void initViews() {
        initToolBar();
        if (UserInfoManager.getUserInfo().getRole().equals(Contracts._Role_UKE)) {
            initDistributorMultiAdapter();
        } else {
            initNormalMultiAdapter();
        }
        rootRecycler.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        rootRecycler.setAdapter(mAdapter);
//        initData();
//        login();
//        getSmsCode();
    }

    private void initDistributorMultiAdapter() {
        //        initDistributorMenuData();
        mViewItems_Distributor = new ArrayList<>();
//        mViewItems_Distributor.add(new MultiItem(_Header_Normal));
        mViewItems_Distributor.add(new MultiItem(_Header_Distributor));
        mViewItems_Distributor.add(new MultiItem(_Banner));
        mViewItems_Distributor.add(new MultiItem(_Menu_Distributor));
        mAdapter = new RootAdapter(mViewItems_Distributor);
    }

    private void initNormalMultiAdapter() {
        mViewItems_Distributor = new ArrayList<>();
        mViewItems_Distributor.add(new MultiItem(_Header_Normal));
//        mViewItems_Distributor.add(new MultiItem(_Header_Distributor));
        mViewItems_Distributor.add(new MultiItem(_Banner));
        mViewItems_Distributor.add(new MultiItem(_Menu_Normal));
        mAdapter = new RootAdapter(mViewItems_Distributor);
    }

    private void initMultiAdapter() {
//        initDistributorMenuData();
        mViewItems_Distributor = new ArrayList<>();
//        mViewItems_Distributor.add(new MultiItem(_Header_Normal));
        mViewItems_Distributor.add(new MultiItem(_Header_Distributor));
        mViewItems_Distributor.add(new MultiItem(_Banner));
        mViewItems_Distributor.add(new MultiItem(_Menu_Distributor));
        mAdapter = new RootAdapter(mViewItems_Distributor);
    }

    private void initData() {


    }

    private List<HomeMenuItem> initDistributorMenuData() {
//        mMenuItemList_Distributor = new ArrayList<>();
        List<HomeMenuItem> itemList = new ArrayList<>();
        itemList.add(new HomeMenuItem("我的团队", R.mipmap.icon_team, 2));
        itemList.add(new HomeMenuItem("我的业绩", R.mipmap.icon_income, 9));
//        mMenuItemList_Distributor.add(new HomeMenuItem("我的金币", R.mipmap.icon_coin, 3));
//        mMenuItemList_Distributor.add(new HomeMenuItem("巧手搭配", R.mipmap.icon_collocation, 4));
//        itemList.add(new HomeMenuItem("快速查询", R.mipmap.icon_transport, 5));
//        itemList.add(new HomeMenuItem("优客客服", R.mipmap.icon_custom_service, 6));
        itemList.add(new HomeMenuItem("新手中心", R.mipmap.icon_help, 7));
        itemList.add(new HomeMenuItem("我的卡券", R.mipmap.my_coupon_icon, 8));
        return itemList;
    }

    private List<HomeMenuItem> initNormalMenuData() {
        List<HomeMenuItem> itemList = new ArrayList<>();
        itemList.add(new HomeMenuItem("我的会员", R.mipmap.icon_member, 0));
//        itemList.add(new HomeMenuItem("我的团队", R.mipmap.icon_team, 2));
        itemList.add(new HomeMenuItem("我的业绩", R.mipmap.icon_income, 1));
        itemList.add(new HomeMenuItem("我的金币", R.mipmap.icon_coin, 3));
//        mMenuItemList_Distributor.add(new HomeMenuItem("巧手搭配", R.mipmap.icon_collocation, 4));
//        itemList.add(new HomeMenuItem("快速查询", R.mipmap.icon_transport, 5));
//        itemList.add(new HomeMenuItem("优客客服", R.mipmap.icon_custom_service, 6));
        itemList.add(new HomeMenuItem("新手中心", R.mipmap.icon_help, 7));
        itemList.add(new HomeMenuItem("我的卡券", R.mipmap.my_coupon_icon, 8));
        return itemList;
    }


    private void initToolBar() {
        setHasOptionsMenu(true);
        toolBar.setTitle("");
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolBar);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.menu_home_page, menu);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private class MultiItem implements MultiItemEntity {

        private int itemType;

        private MultiItem(int itemType) {
            this.itemType = itemType;
        }

        @Override
        public int getItemType() {
            return itemType;
        }
    }

    private void onMenuItemClick(int type) {
        switch (type) {
            case 0:
                toMyMembers();
                break;
            case 1:
//                toMyIncome();
                toMyPerformance();
                break;
            case 2:
                toMyTeamGroup();
                break;

            case 3:
                toMyCoins();
                break;
            case 8:
                toMyCoupons();
                break;
            case 9:
                toUkePerformance();
                break;
        }
    }

    private void toUkePerformance() {
        Intent intent = new Intent(mContext, UkePerformanceActivity.class);
        startActivity(intent);
    }

    private void toMyCoins() {
        Intent intent = new Intent(mContext, MyGoldCoinsActivity.class);
        startActivity(intent);
    }

    private void toMyCoupons() {
        Intent intent = new Intent(mContext, MyCouponActivity.class);
        startActivity(intent);
    }

    private void toMyIncome() {
        Intent intent = new Intent(getActivity(), MyIncomeActivity.class);
        startActivity(intent);
    }

    private void toMyMembers() {
        Intent intent = new Intent(getActivity(), MyMembersActivity.class);
        startActivity(intent);
    }

    private void toMyTeamGroup() {
        Intent intent = new Intent(getContext(), MyTeamActivity.class);
        startActivity(intent);
    }

    private void toMyVisitors() {
        Intent intent = new Intent(getActivity(), VisitorsActivity.class);
        startActivity(intent);
    }

    private void toMyOrders() {
        Intent intent = new Intent(mContext, MySalePerformanceActivity.class);
        startActivity(intent);
    }

    private void toMyPerformance() {
        Intent intent = new Intent(getContext(), MyPerformanceActivity.class);
        startActivity(intent);
    }

    private class RootAdapter extends BaseMultiItemQuickAdapter<MultiItem, BaseViewHolder> {

        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param data A new list is created out of this one to avoid mutable list
         */
        public RootAdapter(List<MultiItem> data) {
            super(data);
            addItemType(_Header_Distributor, R.layout.home_header_distributor);
            addItemType(_Banner, R.layout.home_banner_layout);
            addItemType(_Menu_Distributor, R.layout.home_menu_distributor);
            addItemType(_Menu_Normal, R.layout.home_menu_normal);
            addItemType(_Header_Normal, R.layout.home_header_normal);
        }

        @Override
        protected void convert(BaseViewHolder holder, MultiItem item) {
            switch (item.getItemType()) {
                case _Header_Distributor:
                    mAvatar_Distributor = holder.getView(R.id.avatar_iv);
                    ImageLoader.getInstance().displayImage(UserInfoManager.getUserInfo().getImageUrl(),
                            mAvatar_Distributor,
                            DisplayImageOptionsManager.getInstance().getAvatarOptions());
                    holder.getView(R.id.sale_performance).setOnClickListener(v -> {
                        toMyOrders();
                    });
                    holder.setText(R.id.user_name_tv, UserInfoManager.getUserInfo().getName());
                    holder.setText(R.id.user_login_name_tv, "No." + UserInfoManager.getUserInfo().getLoginName());
//                    new GetUserSaleInfoPresenter(new GetUserSalesContractor.View() {
//                        @Override
//                        public void onGetUserSalesInfoSuccess(UserSalesInfo info) {
//                            holder.setText(R.id.sales_count_tv, String.valueOf(info.getSaleQuantity()));
//                        }
//
//                        @Override
//                        public void onLoading(String loadingMessage) {
//                            holder.getView(R.id.sale_performance).setVisibility(View.GONE);
//                        }
//
//                        @Override
//                        public void onLoadFinished() {
//                            holder.getView(R.id.sale_performance).setVisibility(View.VISIBLE);
//                        }
//
//                        @Override
//                        public void onFail(int code, String errorMessage) {
//                            holder.getView(R.id.sales_count_tv).setVisibility(View.GONE);
//                            Toast.makeText(mContext, "获取销售数量失败：" + errorMessage, Toast.LENGTH_SHORT).show();
//                        }
//                    }).getUserSaleInfo();
//                    holder.getView(R.id.my_visitors).setOnClickListener(v -> toMyVisitors());
                    break;

                case _Header_Normal:
                    mAvatar_normal = holder.getView(R.id.avatar_iv);
                    ImageLoader.getInstance().displayImage(UserInfoManager.getUserInfo().getImageUrl(),
                            mAvatar_normal,
                            DisplayImageOptionsManager.getInstance().getAvatarOptions());
                    holder.setText(R.id.user_name_tv, UserInfoManager.getUserInfo().getName());
                    holder.setText(R.id.user_login_name_tv, "No." + UserInfoManager.getUserInfo().getLoginName());
//                    holder.getView(R.id.sale_performance).setOnClickListener(v ->
////                            toMyPerformance()
//                                    toMyOrders()
//                    );
//                    mAvatar_normal.setOnClickListener(v -> {
//                        Intent intent = new Intent(mContext, LoginActivity.class);
//                        startActivity(intent);
//                    });
                    break;
                case _Banner:
                    mBannerView = holder.getView(R.id.banner_view);
                    ErrorCallBack errorCallBack = new ErrorCallBack();
                    final LoadService loadService = new LoadSir.Builder()
                            .addCallback(errorCallBack)
                            .addCallback(new LoadingCallBack())
                            .build().register(mBannerView, new Callback.OnReloadListener() {
                                @Override
                                public void onReload(View v) {

                                }
                            });
                    new GetHomeBannerPresenter().getBannerInfo(new GetHomePageBannerContractor.View() {
                        @Override
                        public LoadService getLoadService() {
                            return loadService;
                        }

                        @Override
                        public Callback getErrorCallBack() {
                            return errorCallBack;
                        }

                        @Override
                        public void onGetBannerInfoSuccess(List<HomeBannerInfo> list) {
                            mBannerView.setBannerResourceInfo(list, new CirculatingBannerView.BannerImageListener() {
                                @Override
                                public void displayImage(BannerData data, ImageView imageView) {
                                    ImageLoader.getInstance().displayImage(((HomeBannerInfo) data).getPicUrl(),
                                            imageView,
                                            DisplayImageOptionsManager.getInstance().getDefaultOptions());
                                }

                                @Override
                                public void onImageClickListener(BannerData data, int position, View view) {

                                }
                            });
                            mBannerView.startImageCycle();
                        }

                        @Override
                        public void onLoading(String loadingMessage) {

                        }

                        @Override
                        public void onLoadFinished() {

                        }

                        @Override
                        public void onFail(int code, String errorMessage) {

                        }
                    });
                    break;
                case _Menu_Distributor:
                    mMenu_Recycler_Distributor = holder.getView(R.id.menu_recycler);
                    mMenuItemList_Distributor = initDistributorMenuData();
                    mMenu_Recycler_Distributor.setLayoutManager(new GridLayoutManager(getActivity(), 4));
                    mMenu_Recycler_Distributor.setAdapter(new BaseQuickAdapter<HomeMenuItem, BaseViewHolder>(R.layout.home_menu_item, mMenuItemList_Distributor) {
                        @Override
                        protected void convert(BaseViewHolder viewHolder, HomeMenuItem item) {
                            viewHolder.setText(R.id.menu_title, item.getTitle())
                                    .setImageResource(R.id.menu_icon, item.getIconRes())
                                    .getConvertView().setOnClickListener(v ->
                                    onMenuItemClick(item.getType())
                            );
                        }
                    });
                    break;
                case _Menu_Normal:
                    mMenu_Recycler_Normal = holder.getView(R.id.menu_recycler);
                    mMenuItemList_Normal = initNormalMenuData();
                    mMenu_Recycler_Normal.setLayoutManager(new GridLayoutManager(getActivity(), 4));
                    mMenu_Recycler_Normal.setAdapter(new BaseQuickAdapter<HomeMenuItem, BaseViewHolder>(R.layout.home_menu_item, mMenuItemList_Normal) {
                        @Override
                        protected void convert(BaseViewHolder viewHolder, HomeMenuItem item) {
                            viewHolder.setText(R.id.menu_title, item.getTitle())
                                    .setImageResource(R.id.menu_icon, item.getIconRes())
                                    .getConvertView().setOnClickListener(v ->
                                    onMenuItemClick(item.getType())
                            );
                        }
                    });
                    break;
            }

        }

    }

}
